package hu.debrecen.adastra.card.web;

import hu.debrecen.adastra.card.repository.domain.Account;
import hu.debrecen.adastra.card.service.GameStoreService;
import hu.debrecen.adastra.card.service.SocialUserService;
import hu.debrecen.adastra.card.web.resolver.AutowiredHandlerAnnotationArgumentResolver.AutowiredHandler;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.web.ConnectSupport;
import org.springframework.social.facebook.api.Facebook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.NativeWebRequest;

@Controller
public class HomeController extends AbstractController {

	private static final Logger LOGGER = LoggerFactory.getLogger(HomeController.class);

	private final ConnectionFactoryLocator connectionFactoryLocator;

	private final GameStoreService gameService;

	private final ConnectSupport connectSupport;

	@Inject
	public HomeController(final GameStoreService gameService, final ConnectionFactoryLocator connectionFactoryLocator, final SocialUserService socialUserService) {
		super(socialUserService);
		this.gameService = gameService;
		this.connectionFactoryLocator = connectionFactoryLocator;
		this.connectSupport = new ConnectSupport();
	}

	@RequestMapping(value = { "", "/" })
	public String index(@AutowiredHandler final Account account, final Model model) {

		HomeController.LOGGER.debug("{} visites index page.", account.getUsername());

		try {
			model.addAttribute("gameId", this.gameService.getGameByAccount(account).getGameId());
		} catch (Exception e) {
			// empty catch
		}

		return "index";
	}

	@RequestMapping(value = "/signin")
	public String signin(final NativeWebRequest request, final Model model) {
		ConnectionFactory<Facebook> connectionFactory = this.connectionFactoryLocator.getConnectionFactory(Facebook.class);
		return String.format("redirect:%s/facebook", this.connectSupport.buildOAuthUrl(connectionFactory, request));
	}

	@RequestMapping("/maintenance")
	public String maintenance() {
		return "maintenance";
	}

}
